package com.ysx.ch04;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CalAspect {

    private static final int MAX=10;
    private static final String MESSAGE_SUCCESS ="我会算";
    private static final String MESSAGE_FAILURE ="我不会算";

    private boolean check(int x, int y){
        boolean rs =x<MAX && y<MAX;
        if(rs){
            System.out.println("参数检验通过 继续执行后面的代码");
        }else{
            System.out.println("参数检验不通过 终止执行...");
        }

        return rs;
    }

    @Around(value = "execution(int com.ysx.ch04.Cal.add(int,int))")
    public Object check(ProceedingJoinPoint pjp){

        Object rs=null;
        Object[] args = pjp.getArgs();

        int x = (int)args[0];
        int y = (int)args[1];
        if(check(x,y)){
           try{
               rs =pjp.proceed();
               printSuccess();

               if((int)rs ==8){
                   print8((int)rs,x,y);
               }

           }catch (Throwable exception){
               System.out.println(exception);
               printFailure();
           }

        }
        rs=0;
        return rs;

    }

    private void printSuccess(){
        System.out.println(MESSAGE_SUCCESS);
    }
    private void printFailure(){
        System.out.println(MESSAGE_FAILURE);
    }

    private void print8(int rs,int x, int y){
        if(rs ==8){
            System.out.println("x="+x+" y="+y);
        }
    }

}
